<?php
/**
 * 
 * @author Bui Thi Ngoc Lan <nglanbt@gmail.com>
 *
 */
class QuizzesPage extends Page {
	static $allowed_children = array("Question");
	static $default_child = "Question";
}
class QuizzesPage_Controller extends Page_Controller {
	public function init() {
		parent::init();
		Requirements::css('quizzes/css/quizzes.css');
		Requirements::javascript('quizzes/javascript/jquery.min.js');
		Requirements::javascript('quizzes/javascript/quizzes.js');
	}
	function QuestionList(){
		$questionList = DataObject::get('Question', 'ParentID = '.$this->ID);
		return $questionList;
	}
	function SubmitTest(){
		if ($_POST) {
			$answerList = $_POST['Answer'];
			$score = 0;
			foreach ($answerList as $answerID) {
				$answer = DataObject::get_by_id('Answer', $answerID);
				$score += $answer->Score;
			}
			$content['Result'] = "Your score is: $score";
			
		}
		return $this->customise($content)->renderWith(array('QuizzesPage', 'Page'));
	}
}
class Question extends Page {
	static $has_many = array(
		'Answer' => 'Answer'
	);
	function getCMSFields(){
		$fields = parent::getCMSFields();
		$answerTableList = new ComplexTableField(
			$this,
			'Answer',
			'Answer',
			array(
				'Content' => 'Content',
				'Score' => 'Score'
			),
			'getCMSField_popup',
			'QuestionID = '. $this->ID			
		);
		$fields->addFieldToTab(
			'Root.Answer',
			$answerTableList
		);
		return $fields;
	}
}
class Answer extends DataObject {
	static $db = array(
		'Content' => "Text",
		'Score' => 'Int'
	);
	static $has_one = array(
		'Question' => 'Question'
	);
	function getCMSField_popup(){
		$fields = new FieldList();
		$fields->push(new TextField('Score', 'Score'));
		$fields->push(new TextareaField('Content', 'Content'));
		return $fields;
	}
	protected function validate() {
		$result = new ValidationResult();
		if(!is_numeric($this->record['Score'])){
			$result->error('Score is not a number');
		}
		if($this->record['Content']==''){
			$result->error('Content is required');
		}
		$this->extend('validate', $result);
		return $result;
	}
}